/**
 * 检查中断
 * {Args: 1100}
 *
 * @author fireway
 * @since 2019年 02月 13日 星期三 06:35:15 CST
 */
package concurrency;

import java.util.concurrent.TimeUnit;

class NeedsCleanup {
    private final int mID;

    public NeedsCleanup(int id) {
        mID = id;
        System.out.println("NeedsCleanup id=" + mID);
    }

    public void cleanup() {
        System.out.println("Cleaning up id=" + mID);
    }
}

class Blocked3 implements Runnable {
    private volatile double mVD = 0.0;

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                // point1
                NeedsCleanup nc1 = new NeedsCleanup(1);
                try {
                    System.out.println("Sleeping 1s");
                    TimeUnit.SECONDS.sleep(1);
                    // point2
                    NeedsCleanup nc2 = new NeedsCleanup(2);
                    // Guarantee proper cleanup of nc2:
                    try {
                        System.out.println("Calculating");
                        long startTime = System.nanoTime();
                        // A time-consuming, non-blocking operation:
                        for (int i = 1; i < 2500000; i++) {
                            mVD = mVD + (Math.PI + Math.E) / mVD;
                        }
                        long duration = System.nanoTime() - startTime;
                        System.out.println("Finished time-consuming operation, duration=" + duration);
                    } finally {
                        nc2.cleanup();
                    }
                } finally {
                    nc1.cleanup();
                }
                System.out.println("Exiting via while() test");
            }
        } catch (InterruptedException e) {
            System.out.println("Exiting via InterruptedException");
            e.printStackTrace();
        }
    }
}

public class InterruptingIdiom {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("usage: java InterruptingIdiom delay-in-mS");
            System.exit(1);
        }
        Thread t = new Thread(new Blocked3());
        t.start();

        int timeout = Integer.parseInt(args[0]);
        try {
            TimeUnit.MILLISECONDS.sleep(timeout);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t.interrupt();
    }
}
